package com.santiao.youxiang.ui.activity

import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.util.Base64
import android.util.Log
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.allen.library.shape.ShapeTextView
import com.santiao.youxiang.bean.EmailBean
import com.gyf.immersionbar.ImmersionBar
import com.santiao.publics.ui.SettingFragment
import com.santiao.youxiang.MainActivity
import com.santiao.youxiang.R
//import com.lazyliuzy.commonui.utils.lzy.LZYADSUtils
//import kotlin.jvm.java
import com.santiao.youxiang.databinding.ActivityEmailListBinding
import com.santiao.youxiang.ext.thrillClickListener
import com.santiao.youxiang.ui.adapter.EmailAdapter
import com.santiao.youxiang.ui.adapter.EmailSelectAdapter
import com.santiao.youxiang.ui.fragment.HomeViewModel
import com.santiao.youxiang.ui.widget.LoadingDiaLog
import com.sun.mail.imap.IMAPFolder
import com.sun.mail.imap.IMAPStore
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import me.leefeng.promptlibrary.PromptButton
import me.leefeng.promptlibrary.PromptDialog
import java.nio.charset.Charset
import java.util.Properties
import javax.mail.Flags
import javax.mail.Folder
import javax.mail.Message
import javax.mail.Multipart
import javax.mail.Part
import javax.mail.Session
import javax.mail.internet.MimeMessage
import javax.mail.search.FlagTerm

class EamilListActivity: AppCompatActivity() {
    private lateinit var binding: ActivityEmailListBinding
//    private lateinit var lzyadsUtils: com.lazyliuzy.commonui.utils.lzy.LZYADSUtils
var type_a="" //1收件箱 2已发送 3草稿箱 4垃圾邮件 5已删除
    var tabemailcode=listOf<Int>(1,2,4,3,5)
    var type=0

    var del_list: MutableList<Long>?=mutableListOf() //存储要删除的pid
    var pageNum=1
    var pageSize=10
    var nametype=""

    var slePosition=1
    lateinit var emailBean:EmailBean
//    private val HviewModel: HomeViewModel by viewModels()
    private lateinit var HviewModel: HomeViewModel

    private lateinit var eadapter: EmailAdapter
    private lateinit var sadapter: EmailSelectAdapter

    var struri=""
    // 在类顶部定义
    val REQUEST_STORAGE_PERMISSION = 1001  // 可以是任意唯一整数

    companion object {
        // 定义一个静态方法来创建Intent
        // 定义一个静态方法来创建Intent并携带uri数据
        fun startActivity(context: Context?,type: String /*bundle: Bundle?*/) {

            val intent = Intent(context, EamilListActivity::class.java).apply {


                putExtra("type", type)

            }

            context!!.startActivity(intent)

//            val intent = Intent(context, EamilListActivity::class.java)
//            if (bundle != null) {
//                intent.putExtras(bundle)  // 使用 bundle 传递数据
//            }
//            context?.startActivity(intent)

        }



    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityEmailListBinding.inflate(layoutInflater)
        setContentView(binding?.root)
        type_a= intent.getStringExtra("type").toString()
        ImmersionBar.with(this)
            .transparentStatusBar()
            .statusBarDarkFont(true)
            .transparentNavigationBar()
            .init()
        initViews(type_a)
        initRv()

        initclick()

        SettingFragment.adLoad2(0,null,binding.flContent3,this,this);
    }

    fun onRefreshData(){
        binding!!.refreshLayout.autoRefresh()
    }

     fun initViews(type: String) {
//         var tabTitle=listOf<String>("收件箱", "未读", "已发送", "星标邮件", "草稿箱", "已删除")
//         var tabemailcode=listOf<Int>(1,2,3,5,4,6)
//         binding.title.text=tabTitle[type_a.toInt()]
         when(type_a){

             "2"->{
                binding.title.text="未读"
             }
             "3"->{
                 binding.title.text="已发送"
             }
             "4"->{
                 binding.title.text="草稿箱"
             }
             "5"->{
                 binding.title.text="星标邮件"
             }
             "6"->{
                 binding.title.text="已删除"
             }
         }

         HviewModel= MainActivity.HviewModel
//        initad()
         HviewModel.emailList2.value?.clear()

         android.os.Handler().postDelayed({
             HviewModel.currentEmailType.value=type.toInt()
             onRefreshData()
             initdata()
         }, 500)



         Log.e("initViews: ",type.toInt().toString() )

         initclick()


        binding.toolbarBack.setOnClickListener { onBackPressed() }

         when(type){
             "1"->{

             }
         }

//          emailBean=intent.getSerializableExtra("email") as EmailBean
//         type_a=intent.getIntExtra("type",0)



    }

    fun gorecover(position: Int){

            if (HviewModel.currentPostType.value=="126"||HviewModel.currentPostType.value=="163"){
                when(position){
                    1 -> nametype="INBOX"
                    2 -> nametype="已发送"
                    3 -> nametype="草稿箱"
                    4 -> nametype="垃圾邮件"
                    5 ->nametype= "已删除"
                    else -> if (HviewModel.currentPostType.value=="126") "病毒邮件" else "病毒文件夹"
                }
            }else if (HviewModel.currentPostType.value=="aliyun") {
                when(position){
                    1 -> nametype="INBOX"
                    2 -> nametype="已发送"
                    3 -> nametype="草稿"
                    4 -> nametype="垃圾邮件"
                    5 -> nametype="已删除邮件"
                    else -> "INBOX"
                }
            }else{
                when(position) {
                    1 ->nametype= "INBOX"
                    2 ->nametype= "Sent Messages"
                    3 ->nametype= "Drafts"
                    4 ->nametype= "Junk"
                    5 ->nametype= "Deleted Messages"
                    else -> "INBOX"
                }
            }

        sadapter?.data?.clear()
        sadapter?.notifyDataSetChanged()
        rcoverbyList(del_list!!)
        onRefreshData()
    }

    fun recoverdialog(){
        val promptDialog = PromptDialog(this@EamilListActivity);
        val cancel = PromptButton("取消", null)
        cancel.textColor = Color.parseColor("#0076ff")
        cancel.textSize=16f
        val rece= PromptButton("收件箱") {
//            nametype="收件箱"
            gorecover(1)
        }

        val send= PromptButton("已发送"){
//            nametype="已发送"
            gorecover(2)
        }

        val keep= PromptButton("草稿箱"){
//            nametype="草稿箱"
            gorecover(3)
        }
        cancel.textSize=16f
        rece.textSize=16f
        keep.textSize=16f
        send.textSize=16f
//            keep.textColor=Color.RED
        promptDialog.showAlertSheet(
            "", true, cancel,
            keep,
            send,
            rece
        )

    }

    private fun deldialog() {
        val dialog = Dialog(this@EamilListActivity, R.style.MyDialog)
//        dialog.setCancelable(false)
//        dialog.setCanceledOnTouchOutside(false)
        dialog.setContentView(R.layout.dialog_del);
//        updateTextColor(dialog)
        dialog.window?.setLayout(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )
        //底部弹出的Dialog
        dialog.window?.setGravity(Gravity.CENTER);
        var tvtitle=dialog.findViewById<TextView>(R.id.tv_title)
        var tvdes=dialog.findViewById<TextView>(R.id.tv_des)
//        var etdes=dialog.findViewById<EditText>(R.id.et_des)
        var close=dialog.findViewById<ShapeTextView>(R.id.tv_cancel)
//        var checkin=dialog.findViewById<ShapeTextView>(R.id.tv_check)
        var confrim=dialog.findViewById<ShapeTextView>(R.id.tv_confrim)

        tvtitle.text="删除邮件"
        tvdes.text="是否删除邮件？"

        dialog.show()

        close.thrillClickListener {
            dialog.cancel()
        }

        confrim.thrillClickListener {
            sadapter?.data?.clear()
            sadapter?.notifyDataSetChanged()
//                        onRefreshData()
            deletebyList(del_list!!)
            onRefreshData()

            dialog.dismiss()
//            dialog.cancel()
        }


    }

    fun initclick(){

        binding.ivEdit.thrillClickListener {
            val layoutManager2 = LinearLayoutManager(this@EamilListActivity, LinearLayoutManager.VERTICAL, false)
            Log.e("initrv: ", "2")

        binding!!.rvEmail?.layoutManager = layoutManager2
        binding!!.rvEmail?.adapter = sadapter
            binding.flMore.visibility=View.VISIBLE
            binding.toolbar.visibility=View.GONE
            binding.toolbar2.visibility=View.VISIBLE

            if (type_a=="5"){
                binding.tvRecover.visibility=View.VISIBLE
            }

        }

        binding.tvCanel.thrillClickListener {
            val layoutManager2 = LinearLayoutManager(this@EamilListActivity, LinearLayoutManager.VERTICAL, false)
            Log.e("initrv: ", "2")

            binding!!.rvEmail?.layoutManager = layoutManager2
            binding!!.rvEmail?.adapter = eadapter
            binding.flMore.visibility=View.GONE
            binding.toolbar.visibility=View.VISIBLE
            binding.toolbar2.visibility=View.GONE

        }

        binding.tvFinish.thrillClickListener {
            binding.tvCanel.performClick()
        }

        binding.ck.thrillClickListener {
            if (binding.ck.isChecked){
                sadapter?.toggleAll(true)
            }else
            sadapter?.toggleAll(false)
        }

        binding.tvDel.thrillClickListener {
            del_list?.clear()
            sadapter?.data?.forEachIndexed { index,itda->
                Log.e("uid123: ",itda.uid.toString() )
                if (itda.isChecked){

                    del_list!!.add(itda.uid)



//                    tryToDeleteEmail(HviewModel.postList.value..pAddress, currentPost.pCode,emailBean.uid)
                }

            }

            if (del_list.isNullOrEmpty()){
                Toast.makeText(this@EamilListActivity,"没有要删除的邮件", Toast.LENGTH_LONG).show()
            }else{
                lifecycleScope.launch {
                    withContext(Dispatchers.Main)  {
                        deldialog()

                    }

                    withContext(Dispatchers.IO)  {
                        try {

                        }catch (e: Exception){
                            Log.e( "deletebyList: ",e.toString() )
                        }

                    }

                }
            }
        }

        binding.tvRecover.thrillClickListener {
            del_list?.clear()
            sadapter?.data?.forEachIndexed { index,itda->
                Log.e("uid123: ",itda.uid.toString() )
                if (itda.isChecked){

                    del_list!!.add(itda.uid)

//                    tryToDeleteEmail(HviewModel.postList.value..pAddress, currentPost.pCode,emailBean.uid)
                }

            }

            if (del_list.isNullOrEmpty()){
                Toast.makeText(this@EamilListActivity,"没有要恢复的邮件", Toast.LENGTH_LONG).show()
            }else{
                lifecycleScope.launch {
                    withContext(Dispatchers.Main)  {
                        recoverdialog()

                    }

                    withContext(Dispatchers.IO)  {
                        try {

                        }catch (e: Exception){
                            Log.e( "rcoverbyList: ",e.toString() )
                        }

                    }

                }
            }
        }

        binding!!.refreshLayout.setOnRefreshListener{
            if (HviewModel.postList.value.isNullOrEmpty()){
                binding!!.refreshLayout.finishRefresh(false)
                Toast.makeText(this@EamilListActivity,"未绑定邮箱",Toast.LENGTH_SHORT).show()
                return@setOnRefreshListener
            }
            pageNum=1
            val currentPost=HviewModel.postList.value?.first { its -> its.pid== HviewModel.currentPost.value }
            if (currentPost!=null) {
                tryToLoginEmail(currentPost.pAddress, currentPost.pCode)
            }
        }

        binding!!.refreshLayout.setOnLoadMoreListener {
            if (HviewModel.postList.value.isNullOrEmpty()){
                binding!!.refreshLayout.finishLoadMore(false)
                Toast.makeText(this@EamilListActivity,"未绑定邮箱",Toast.LENGTH_SHORT).show()
                return@setOnLoadMoreListener
            }
            pageNum++
            val currentPost=HviewModel.postList.value?.first { its -> its.pid== HviewModel.currentPost.value }
            if (currentPost!=null) {
                tryToLoginEmail(currentPost.pAddress, currentPost.pCode)
            }
        }

//        binding.detailDelete.thrillClickListener{
//            val currentPost=HviewModel.postList.value?.first { its -> its.pid== HviewModel.currentPost.value }
//            if (currentPost!=null) {
//                tryToDeleteEmail(currentPost.pAddress, currentPost.pCode,emailBean.uid)
//            }
//        }
//
//
//        binding.detailReply.thrillClickListener{
//
//            val bundle=Bundle()
//            bundle.putInt("type",1)
//            bundle.putString("subject",emailBean.subject)
//            bundle.putString("address",emailBean.fromEmail.substringAfter("<").substringBefore(">"))
////            LZYBaseActivity.forward<EmailWriteActivity>(this@EmailDetailActivity,bundle)
//
//        }

    }

    fun deletebyList(d_list :MutableList<Long>){

        d_list.forEachIndexed { index,itda ->
            val currentPost=HviewModel.postList.value?.first { its -> its.pid== HviewModel.currentPost.value } //当前账号
            if (currentPost!=null) {
                tryToDeleteEmail(currentPost.pAddress, currentPost.pCode,itda)
            }
        }
    }

    fun rcoverbyList(d_list :MutableList<Long>){

        d_list.forEachIndexed { index,itda ->
            val currentPost=HviewModel.postList.value?.first { its -> its.pid== HviewModel.currentPost.value } //当前账号
            if (currentPost!=null) {
                restoreEmail(currentPost.pAddress, currentPost.pCode,itda)
            }
        }
    }


    fun switchItem(position: Int) {

    }

    fun initRv(){


        eadapter=EmailAdapter()


        val layoutManager = LinearLayoutManager(this@EamilListActivity, LinearLayoutManager.VERTICAL, false)
        Log.e("initrv: ", "2")
//        Camadapter

        binding!!.rvEmail?.layoutManager = layoutManager
        binding!!.rvEmail?.adapter = eadapter

        eadapter.setEmptyView(R.layout.layout_empty)


        //item整体点击事件
        eadapter.setOnItemClickListener { adapter, view, position ->
            Log.e("initRv: ", "你点击了")

//            val item = adapter.data[position] as HomeCamBean  // 明确类型
//            val userId = item.userId.toString()
//            val chanelId = item.channelID.toString()
//            val token = item.token.toString()

            if (type_a.toInt()==3){
                val bundle=Bundle()
                bundle.putInt("type", 1)
                bundle.putSerializable("email", eadapter.data.get(position))
                EmailWriteActivity.startActivity(this@EamilListActivity,bundle)

            }else{
                val bundle=Bundle()
                bundle.putInt("type", 0)
                bundle.putSerializable("email", eadapter.data.get(position))
                EamilDetailActivity.startActivity(this@EamilListActivity,bundle)
            }


//            LZYBaseActivity.forward<EmailDetailActivity>(mContext,bundle)
//            var userIds= adapter.data.get(0)
//            val cam = LitePal.where("userId = ? ", userId).findFirst(liveCam::class.java)
        }



        sadapter= EmailSelectAdapter()


        val layoutManager2 = LinearLayoutManager(this@EamilListActivity, LinearLayoutManager.VERTICAL, false)
        Log.e("initrv: ", "2")
//        Camadapter

//        binding!!.rvEmail?.layoutManager = layoutManager2
//        binding!!.rvEmail?.adapter = sadapter

//        eadapter.setEmptyView(R.layout.layout_empty)


        //item整体点击事件
        sadapter.setOnItemClickListener { adapter, view, position ->
            Log.e("initRv: ", "你点击了")

//            val item = adapter.data[position] as HomeCamBean  // 明确类型
//            val userId = item.userId.toString()
//            val chanelId = item.channelID.toString()
//            val token = item.token.toString()
            val ckList = view.findViewById<CheckBox>(R.id.ck_list)
            ckList.performClick() // 模拟点击 CheckBox

//            val bundle=Bundle()
//            bundle.putInt("type", 0)
//            bundle.putSerializable("email", eadapter.data.get(position))
//            EamilDetailActivity.startActivity(this@EamilListActivity,bundle)
//            LZYBaseActivity.forward<EmailDetailActivity>(mContext,bundle)
//            var userIds= adapter.data.get(0)
//            val cam = LitePal.where("userId = ? ", userId).findFirst(liveCam::class.java)
        }

        sadapter?.setOnItemChildClickListener { adapter, view, position ->
            when (view.id) {
                R.id.ck_list -> {
                    // 找到对应的 CheckBox

                    Log.e( "ChildClick: ", "点击了")
                    val checkBox = view as CheckBox

                    // 获取当前数据项
                    val item = sadapter?.data?.get(position)

                    // 更新数据模型中的状态
                    item?.isChecked = checkBox.isChecked

//                    binding.topBar.tvTitle2.text="删除"

                    // 通知 Activity 或 Fragment 状态变化
                    Log.e("Activity", "CheckBox at position $position is now ${checkBox.isChecked}")
//                    onCheckStateChanged(position, checkBox.isChecked)
                }
            }
        }




//        eadapter!!.setOnItemChildClickListener { _, view, position ->
////            if (view.id == R.id.ll_del) {
////                // 删除逻辑
////                delFromdb(billadapter!!.data.get(position).id.toString())
////                billadapter!!.removeAt(position)
////                billadapter!!.notifyItemRemoved(position)
////
////            }
//            val bundle=Bundle()
////            bundle.putInt("type", type)
////            bundle.putSerializable("email", itemData)
////            LZYBaseActivity.forward<EmailDetailActivity>(mContext,bundle)
//
//        }


    }


    @OptIn(DelicateCoroutinesApi::class)
    fun tryToDeleteEmail( email: String, authCode: String,uid:Long) {
        val loadingDiaLog= LoadingDiaLog(this@EamilListActivity,"删除中...")
        loadingDiaLog.show()
        // 在后台线程执行 IMAP 请求
        GlobalScope.launch(Dispatchers.IO) {
            var imapHost: String? =null
            val domain = email.substringAfter("@")
            when (domain) {
                "126.com" -> {
                    imapHost = "imap.126.com"
                }

                "163.com" -> {
                    // 对136.com进行处理
                    imapHost = "imap.163.com"
                }

                "qq.com" -> {
                    // 对qq.com进行处理
                    imapHost = "imap.qq.com"
                }

                else -> {
                    imapHost = "imap.aliyun.com"
                }
            }
            val imapPort = "993"
            val properties = Properties()
            properties["mail.store.protocol"] = "imaps"
            properties["mail.imaps.host"] = imapHost
            properties["mail.imaps.port"] = imapPort

            // 获取Session
            val session = Session.getInstance(properties)
            try {
                // 创建 IMAP 存储连接
                val store = session.getStore("imaps")
                store.connect(imapHost, email, authCode)  // 使用授权码登录
                val folderName=
                    if (HviewModel.currentPostType.value=="126"|| HviewModel.currentPostType.value=="163"){
                        when(HviewModel.currentEmailType.value){
                            1 -> "INBOX"
                            2 -> "INBOX"
                            3 -> "已发送"
                            4 -> "草稿箱"
                            5 -> "垃圾邮件"
                            6 -> "已删除"
                            else -> if (HviewModel.currentPostType.value=="126") "病毒邮件" else "病毒文件夹"
                        }
                    }else if (HviewModel.currentPostType.value=="aliyun") {
                        when(HviewModel.currentEmailType.value){
                            1 -> "INBOX"
                            2 -> "INBOX"
                            3 -> "已发送"
                            4 -> "草稿"
                            5 -> "垃圾邮件"
                            6 -> "已删除邮件"
                            else -> "INBOX"
                        }
                    }else{
                        when(HviewModel.currentEmailType.value) {
                            1 -> "INBOX"
                            2 -> "INBOX"
                            3 -> "Sent Messages"
                            4 -> "Drafts"
                            5 -> "Junk"
                            6 -> "Deleted Messages"
                            else -> "INBOX"
                        }
                    }
                val f=store.getFolder(folderName) as IMAPFolder
                store as IMAPStore
                val idMap: MutableMap<String, String> = HashMap()
                idMap["name"] = "mail poster" // 这里是一个姓名，可以随便写
                idMap["version"] = "7.26"
                idMap["os"] = "android"
                idMap["os-version"] = "1.0.0"
                idMap["vendor"] = "hello" // 随便写
                idMap["contact"] = "${email}" // 是一个邮箱
                store.id(idMap)
                f.open(Folder.READ_WRITE)  // 打开文件夹（只读模式）
                val message=f.getMessageByUID(uid)



                if (type_a.toInt()==5){//彻底删除
                    message.setFlags(Flags(Flags.Flag.DELETED), true) // 直接删除邮件

                    // 完成操作后关闭文件夹
                    f.expunge()
                    f.close(false)
                    store.close()
                }else{//回收站
                    // 获取收件箱或已发送邮件夹
                    val folder = store.getFolder(folderName) as IMAPFolder
                    folder.open(IMAPFolder.READ_WRITE)

                    // 获取回收站文件夹
                    val trashFolder = store.getFolder("Trash") as IMAPFolder
                    trashFolder.open(IMAPFolder.READ_WRITE)

                    // 获取要移动的邮件
//                    val messages = folder.getMessageByUID(uid)
                    val message2 = folder.getMessageByUID(uid)
                    val messages = arrayOf(message2) // Wrap the single message in an array

                    // 移动邮件到回收站
                    (folder as IMAPFolder).moveMessages(messages, trashFolder)

                    // 关闭文件夹
                    folder.close(false)
                    trashFolder.close(false)
                }


                withContext(Dispatchers.Main) {
                    if (type==1)
                        HviewModel.refreshEmail.value=2
                    else
                        HviewModel.refreshEmail.value=1
                    loadingDiaLog.dismiss()
                    Toast.makeText(this@EamilListActivity,"删除邮件成功~", Toast.LENGTH_SHORT).show()
                    finish()
                }
            } catch (e: Exception) {
                e.printStackTrace()
//                LZYLog.i("lzyemail", "邮件：删除邮件失败")
                withContext(Dispatchers.Main) {
                    loadingDiaLog.dismiss()
                    Toast.makeText(this@EamilListActivity,"删除邮件失败！", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    @OptIn(DelicateCoroutinesApi::class)
    fun restoreEmail(email: String, authCode: String, uid: Long) {
        val loadingDiaLog = LoadingDiaLog(this@EamilListActivity, "恢复中...")
        loadingDiaLog.show()

        GlobalScope.launch(Dispatchers.IO) {
            var imapHost: String? = null
            val domain = email.substringAfter("@")
            when (domain) {
                "126.com" -> imapHost = "imap.126.com"
                "163.com" -> imapHost = "imap.163.com"
                "qq.com" -> imapHost = "imap.qq.com"
                else -> imapHost = "imap.aliyun.com"
            }
            val imapPort = "993"
            val properties = Properties().apply {
                this["mail.store.protocol"] = "imaps"
                this["mail.imaps.host"] = imapHost
                this["mail.imaps.port"] = imapPort
            }

            val session = Session.getInstance(properties)
            try {
                val store = session.getStore("imaps")
                store.connect(imapHost, email, authCode)

                val trashFolder = store.getFolder("Trash") as IMAPFolder
                trashFolder.open(Folder.READ_WRITE)

                val originalFolderName =nametype /*"INBOX"*/ // 根据实际情况选择文件夹名称
                val originalFolder = store.getFolder(originalFolderName) as IMAPFolder
                originalFolder.open(Folder.READ_WRITE)

                val message = trashFolder.getMessageByUID(uid)
                val messages = arrayOf(message)

                (trashFolder as IMAPFolder).moveMessages(messages, originalFolder)

                trashFolder.close(false)
                originalFolder.close(false)

                withContext(Dispatchers.Main) {
                    loadingDiaLog.dismiss()
                    Toast.makeText(this@EamilListActivity, "邮件已恢复", Toast.LENGTH_SHORT).show()
                    finish()
                }
            } catch (e: Exception) {
                e.printStackTrace()
                withContext(Dispatchers.Main) {
                    loadingDiaLog.dismiss()
                    Toast.makeText(this@EamilListActivity, "恢复邮件失败", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

  /*  @OptIn(DelicateCoroutinesApi::class)
    fun restoreEmail(email: String, authCode: String, uid: Long) {
        val loadingDiaLog = LoadingDiaLog(this@EamilListActivity, "恢复中...")
        loadingDiaLog.show()

        GlobalScope.launch(Dispatchers.IO) {
            var imapHost: String? = null
            val domain = email.substringAfter("@")
            when (domain) {
                "126.com" -> imapHost = "imap.126.com"
                "163.com" -> imapHost = "imap.163.com"
                "qq.com" -> imapHost = "imap.qq.com"
                else -> imapHost = "imap.aliyun.com"
            }
            val imapPort = "993"
            val properties = Properties().apply {
                this["mail.store.protocol"] = "imaps"
                this["mail.imaps.host"] = imapHost
                this["mail.imaps.port"] = imapPort
            }

            val session = Session.getInstance(properties)
            try {
                val store = session.getStore("imaps")
                store.connect(imapHost, email, authCode)

                // 获取回收站文件夹
                val trashFolder = store.getFolder("Trash") as IMAPFolder
                trashFolder.open(Folder.READ_WRITE)

                // 获取邮件
                val message = trashFolder.getMessageByUID(uid)
                val messages = arrayOf(message)

                // 获取原始文件夹
                val originalFolderName = message.folder.name
                val originalFolder = store.getFolder(originalFolderName) as IMAPFolder
                originalFolder.open(Folder.READ_WRITE)

                // 将邮件从回收站移动回原始文件夹
                (trashFolder as IMAPFolder).moveMessages(messages, originalFolder)

                trashFolder.close(false)
                originalFolder.close(false)

                withContext(Dispatchers.Main) {
                    loadingDiaLog.dismiss()
                    Toast.makeText(this@EamilListActivity, "邮件已恢复", Toast.LENGTH_SHORT).show()
                    finish()
                }
            } catch (e: Exception) {
                Log.e( "restoreEmail: ", e.toString())

                withContext(Dispatchers.Main) {
                    loadingDiaLog.dismiss()
                    Toast.makeText(this@EamilListActivity, "恢复邮件失败", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }*/


    fun initdata(){

        HviewModel.emailList2.observe(this){
            Log.e("initdata: ", it.toString())
            if (it.isNullOrEmpty()){
//                binding.noEmail.visibility=View.VISIBLE
//                binding.emailRecyclerView.visibility=View.GONE
                eadapter.setEmptyView(R.layout.layout_empty)
            }else{
//                binding.noEmail.visibility=View.GONE
//                binding.emailRecyclerView.visibility=View.VISIBLE
            }
//            Log.e("initdata: ", )
            eadapter.data.clear()
            eadapter.setList(it)
            eadapter.notifyDataSetChanged()

            sadapter.data.clear()
            sadapter.setList(it)
            sadapter.notifyDataSetChanged()
//            binding.emailRecyclerView.adapter=adapter
//            binding.emailRecyclerView.layoutManager=LinearLayoutManager(myActivity,LinearLayoutManager.VERTICAL,false)
        }

    }



    fun   initad() {
//        myContext = this@EamilListActivity
//        lzyadsUtils=
//            com.lazyliuzy.commonui.utils.lzy.LZYADSUtils("Task1Activity", this@Task1Activity)
//        com.lazyliuzy.commonui.utils.lzy.LZYADSUtils.loadSimpleAd1(com.lazyliuzy.commonui.databinding.ActivityTask1Binding.flAd)
//        com.lazyliuzy.commonui.utils.lzy.LZYADSUtils.showAdCpTurn()

    }

    fun tryToLoginEmail( email: String, authCode: String) {
        // 在后台线程执行 IMAP 请求
        GlobalScope.launch(Dispatchers.IO) {
            var imapHost: String? =null
            val domain = email.substringAfter("@")
            when (domain) {
                "126.com" -> {
                    imapHost = "imap.126.com"
                }

                "163.com" -> {
                    // 对136.com进行处理
                    imapHost = "imap.163.com"
                }

                "qq.com" -> {
                    // 对qq.com进行处理
                    imapHost = "imap.qq.com"
                }

                else -> {
                    imapHost = "imap.aliyun.com"
                }
            }
            val imapPort = "993"
            val properties = Properties()
            properties["mail.store.protocol"] = "imaps"
            properties["mail.imaps.host"] = imapHost
            properties["mail.imaps.port"] = imapPort

            // 获取Session
            val session = Session.getInstance(properties)
            try {
                // 创建 IMAP 存储连接
                val store = session.getStore("imaps")
                store.connect(imapHost, email, authCode)  // 使用授权码登录
                val folderName=
                    if (HviewModel.currentPostType.value=="126"||HviewModel.currentPostType.value=="163"){
                        when(type_a){

                            "2"->{
                                "INBOX"
//                                binding.title.text="未读"
                            }
                            "3"->{
                                "已发送"
//                                binding.title.text="已发送"
                            }
                            "4"->{
                                "草稿箱"
//                                binding.title.text="草稿箱"
                            }
                            "5"->{
                                "垃圾邮件"
//                                binding.title.text="星标邮件"
                            }
                            "6"->{
                                "已删除"
//                                binding.title.text="已删除"
                            }else -> if (HviewModel.currentPostType.value=="126") "病毒邮件" else "病毒文件夹"
                        }

                      /*  when(HviewModel.currentEmailType.value){
                            1 -> "INBOX"
                            2 -> "INBOX"
                            3 -> "已发送"
                            4 -> "草稿箱"
                            5 -> "垃圾邮件"
                            6 -> "已删除"
                            else -> if (HviewModel.currentPostType.value=="126") "病毒邮件" else "病毒文件夹"
                        }*/
                    }else if (HviewModel.currentPostType.value=="aliyun") {

                        when(type_a){

                            "2"->{
                                "INBOX"
//                                binding.title.text="未读"
                            }
                            "3"->{
                                "已发送"
//                                binding.title.text="已发送"
                            }
                            "4"->{
                                "草稿"
//                                binding.title.text="草稿箱"
                            }
                            "5"->{
                                "垃圾邮件"
//                                binding.title.text="星标邮件"
                            }
                            "6"->{
                                "已删除邮件"
//                                binding.title.text="已删除"
                            }else -> "INBOX"
                        }

                      /*  when(HviewModel.currentEmailType.value){
                            1 -> "INBOX"
                            2 -> "INBOX"
                            3 -> "已发送"
                            4 -> "草稿"
                            5 -> "垃圾邮件"
                            6 -> "已删除邮件"
                            else -> "INBOX"
                        }*/
                    }else{

                        when(type_a){

                            "2"->{
                                "INBOX"
//                                binding.title.text="未读"
                            }
                            "3"->{
                                "Sent Messages"
//                                binding.title.text="已发送"
                            }
                            "4"->{
                                "Drafts"
//                                binding.title.text="草稿箱"
                            }
                            "5"->{
                                "Junk"
//                                binding.title.text="星标邮件"
                            }
                            "6"->{
                                "Deleted Messages"
//                                binding.title.text="已删除"
                            }else -> "INBOX"
                        }

                     /*   when(HviewModel.currentEmailType.value) {
                            1 -> "INBOX"
                            2 -> "INBOX"
                            3 -> "Sent Messages"
                            4 -> "Drafts"
                            5 -> "Junk"
                            6 -> "Deleted Messages"
                            else -> "INBOX"
                        }*/
                    }
                val f=store.getFolder(folderName) as IMAPFolder
                store as IMAPStore
                val idMap: MutableMap<String, String> = HashMap()
                idMap["name"] = "mail poster" // 这里是一个姓名，可以随便写
                idMap["version"] = "7.26"
                idMap["os"] = "android"
                idMap["os-version"] = "1.0.0"
                idMap["vendor"] = "hello" // 随便写
                idMap["contact"] = "${email}" // 是一个邮箱
                store.id(idMap)
                f.open(Folder.READ_ONLY)  // 打开文件夹（只读模式）
                // 获取所有邮件
                val emails= mutableListOf<EmailBean>()
                var getType=0//0代表不足获取  1代表完整获取  -1表示空获取
                if (f.messageCount>0){
                    //获取所有邮件

                    val messages: Array<Message> = if (type_a.toInt() == 2) {
                        // 使用 search 搜索未读邮件（SEEN == false）
                        val unseenFlag = FlagTerm(Flags(Flags.Flag.SEEN), false)
                        val allUnreadMessages = f.search(unseenFlag)

                        // 分页处理
                        val totalCount = allUnreadMessages.size
                        val startIndex = if (pageNum * pageSize > totalCount) 0 else totalCount - pageNum * pageSize
                        val endIndex = totalCount - (pageNum - 1) * pageSize

                        if (startIndex <= 0) {
                            getType = 0
                            allUnreadMessages.takeLast(endIndex).toTypedArray()
                        } else {
                            getType = 1
                            allUnreadMessages.slice(startIndex until endIndex).toTypedArray()
                        }
                    } else {
                        // 原始 getMessages 方式（支持分页）
                        if (f.messageCount - pageSize * pageNum <= 0) {
                            getType = 0
                            f.getMessages(1, f.messageCount - (pageNum - 1) * pageSize)
                        } else {
                            getType = 1
                            f.getMessages(f.messageCount - pageSize * pageNum + 1, f.messageCount - (pageNum - 1) * pageSize)
                        }
                    }




                    /*val messages =
                        if (f.messageCount-pageSize*pageNum<=0) {
                            getType=0
//                            LZYLog.i("lzyemailget","form 1 to ${f.messageCount-(pageNum-1)*pageSize}")
                            f.getMessages(1,f.messageCount-(pageNum-1)*pageSize)
                        }
                        else {
                            getType=1
//                            LZYLog.i("lzyemailget","pageNum:$pageNum,messageCount:${f.messageCount}")
//                            LZYLog.i("lzyemailget","form ${f.messageCount - pageSize*pageNum + 1} to ${f.messageCount-(pageNum-1)*pageSize}")
                            f.getMessages(f.messageCount - pageSize*pageNum + 1, f.messageCount-(pageNum-1)*pageSize)
                        }*/
                    // 输出邮件内容
                    for (message in messages) {
                        message as MimeMessage
                        val emailFrom=decodeBase64AndKeepEmail(message.from.joinToString(", ")).split(" ")
//                        LZYLog.i("lzyemailget","type:${message.contentType}")
                        val contentm= getMailContent(message,true)
                        emails.add(
                            EmailBean(
                                f.getUID(message),
                                emailFrom[0],
                                if (emailFrom.size==1) "<${emailFrom[0]}>" else emailFrom[1],
                                decodeBase64AndKeepEmail(
                                    message.getRecipients(Message.RecipientType.TO)
                                        .joinToString(", ")
                                ),
                                message.sentDate,
                                message.subject,
                                contentm?:""
                            )
                        )
                    }
                }else{
                    getType=-1
                }
                withContext(Dispatchers.Main) {
                    emails.reverse()
                    when(getType){
                        -1 -> {
                            binding!!.refreshLayout.setNoMoreData(true)
                        }

                        0 -> {
                            binding!!.refreshLayout.setNoMoreData(true)
                        }

                        1 -> {
                            binding!!.refreshLayout.setNoMoreData(false)
                        }

                    }
                    if (pageNum==1){
                        HviewModel.emailList2.value=emails
                        Log.e( "tryToLoginEmail: ",emails.toString() )
                    }

                    else{
                        eadapter.addData(emails)
                    }
                }
                // 完成操作后关闭文件夹
                f.close(false)
                store.close()
                withContext(Dispatchers.Main) {
                    if (pageNum==1) {
                        binding!!.refreshLayout.finishRefresh()
//                        LZYLog.i("lzyemailget", "停止刷新")
                    }
                    else {
                        binding!!.refreshLayout.finishLoadMore()
//                        LZYLog.i("lzyemailget", "停止加载更多")
                    }
//                    Toast.makeText(this@EamilListActivity,"获取邮件信息成功~", Toast.LENGTH_SHORT).show()
                }
            } catch (e: Exception) {
                e.printStackTrace()
//                LZYLog.i("lzyemail", "邮件：登录连接失败")
                withContext(Dispatchers.Main) {
                    if (pageNum==1) {
                        binding!!.refreshLayout.finishRefresh()
//                        LZYLog.i("lzyemailget", "停止刷新")
                    }
                    else {
                        binding!!.refreshLayout.finishLoadMore()
//                        LZYLog.i("lzyemailget", "停止加载更多")
                    }
                    Toast.makeText(this@EamilListActivity,"获取邮件信息失败！", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    fun decodeBase64AndKeepEmail(encodedString: String): String {
        // 正则表达式用于匹配 Base64 编码部分，且不区分大小写
        val regex = "=\\?(?i)utf-8\\?b\\?([^?]+)?\\?="

        val matchResults = regex.toRegex().findAll(encodedString)
        val decodedParts = mutableListOf<String>()
        var lastEnd = 0

        // 遍历所有匹配项
        for (match in matchResults) {
            // 添加非 Base64 编码的部分
            decodedParts.add(encodedString.substring(lastEnd, match.range.first))

            // 提取 Base64 编码部分
            val base64Encoded = match.groupValues[1]

            // 解码 Base64 字符串
            val decodedBytes = Base64.decode(base64Encoded, Base64.NO_WRAP)
            val decodedText = String(decodedBytes, Charset.forName("UTF-8"))

            // 添加解码后的文本
            decodedParts.add(decodedText)

            lastEnd = match.range.last + 1
        }

        // 如果还有剩余的部分，直接添加
        decodedParts.add(encodedString.substring(lastEnd))

        return decodedParts.joinToString("")
    }

    @Throws(Exception::class)
    fun getMailContent(part: Part, first: Boolean = true): String {
        val bodyText = StringBuilder()
        val contentType: String = part.contentType.lowercase()

        val isAttachment = contentType.contains("name=") || Part.ATTACHMENT.equals(part.disposition, true)

        when {
            part.isMimeType("text/plain") && !isAttachment -> {
                if (first) return part.content as String
                bodyText.append(part.content as String)
            }

            part.isMimeType("text/html") && !isAttachment -> {
                bodyText.append(part.content as String)
            }

            part.isMimeType("multipart/*") -> {
                val multipart = part.content as Multipart
                for (i in 0 until multipart.count) {
                    bodyText.append(getMailContent(multipart.getBodyPart(i), false))
                }
            }

            part.isMimeType("message/rfc822") -> {
                return getMailContent(part.content as Part, false)
            }
        }
        return bodyText.toString()
    }

    override fun onDestroy() {
        super.onDestroy()

//        initad()
        HviewModel.emailList2.value?.clear()

    }


}